﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using AtletIS.Shared.Data;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using AtletIS.Shared.Helpers;

namespace AtletIS.Shared.Forms
{
    public partial class frmSplitAuto : Form
    {
        private TreeNode tnDiscipline;

        private DisciplineListTableAdapter taDisciplineList = new DisciplineListTableAdapter();
        private PerformancesTableAdapter taPerformances = new PerformancesTableAdapter();

        private aDbDataSet.DisciplineListDataTable dtDisciplineList;
        private aDbDataSet.PerformancesDataTable dtPerformances;
        private aDbDataSet.DisciplineListRow drHeaderDiscipline;

        // Constructor
        public frmSplitAuto(TreeNode tnDiscipline)
        {
            InitializeComponent();

            this.tnDiscipline = tnDiscipline;
            this.Icon = Properties.Resources.AtletIS64;
        }

        // Form Load
        private void frmSplitAuto_Load(object sender, EventArgs e)
        {
            this.lblTitle.Text = this.tnDiscipline.Text;
        }

        // Koniec
        private void tsbClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // Rozdelit vsetkych
        private void rbAll_CheckedChanged(object sender, EventArgs e)
        {
            this.nudHeatsCount.Enabled = !rbAll.Checked;
        }
               
        // Rozdelit
        private void tsbSplit_Click(object sender, EventArgs e)
        {
            DataTable dtSplitHeader;
            int heatCount, lastHeatCount, competitorsCount, splitCount;

            string header = txtHeatsHeader.Text;

            Cursor.Current = Cursors.WaitCursor;

            #region Kontroly

            if (Globals.ActiveCompetition.LanesCount == 0)
            {
                MessageBox.Show("Preteky nemajú zadaný počet dráh.", "Rozdelenie", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (string.IsNullOrEmpty(header))
            {
                MessageBox.Show("Zadajte názov rozdelenia, prosím!", "Rozdelenie", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            #endregion

            #region Pocet behov

            if (rbAll.Checked)
            {
                competitorsCount = DatabaseHelper.GetPerformancesByDisciplineListId(Convert.ToInt32(tnDiscipline.Name)).Rows.Count; 
                heatCount = competitorsCount / Globals.ActiveCompetition.LanesCount;
                lastHeatCount = competitorsCount % Globals.ActiveCompetition.LanesCount;

                if (lastHeatCount > 0)
                {
                    heatCount += 1;
                }
            }
            else
            {
                heatCount = Convert.ToInt32(nudHeatsCount.Value);
            }

            #endregion

            #region Discipliny

            try
            {
                // Vytvori hlavicku rozdelenia
                dtDisciplineList = DatabaseHelper.GetDisciplineListById(Convert.ToInt32(tnDiscipline.Name));
                if (dtDisciplineList != null && dtDisciplineList.Rows.Count > 0)
                {
                    DataRow dr = dtDisciplineList.Rows[0];
                    int secondaryOrder = 1;

                    drHeaderDiscipline = dtDisciplineList.NewDisciplineListRow();

                    drHeaderDiscipline.Name = header;
                    drHeaderDiscipline.ParentId = Convert.ToInt32(dr["ID"]);
                    drHeaderDiscipline.CompetitionId = Convert.ToInt32(dr["CompetitionId"]);
                    drHeaderDiscipline.DisciplineId = Convert.ToInt32(dr["DisciplineId"]);
                    drHeaderDiscipline.CategoryId = Convert.ToInt32(dr["CategoryId"]);
                    drHeaderDiscipline.Order = Convert.ToInt32(dr["Order"]);
                    drHeaderDiscipline.SecondaryOrder = secondaryOrder;
                    drHeaderDiscipline.AutoOrder = DatabaseHelper.GetDisciplineListNewAutoOrder(drHeaderDiscipline.CompetitionId);
                    drHeaderDiscipline.Status = 1;
                    drHeaderDiscipline.MeasurementId = 1;
                    drHeaderDiscipline.Description = string.Empty;
                    drHeaderDiscipline.SetActivePerformanceIdNull();
                    drHeaderDiscipline.SetActivePerformanceHeaderNull();
                    drHeaderDiscipline.ShowSplits = true;
                    drHeaderDiscipline.Active = true;
                    drHeaderDiscipline.Visible = true;
                    drHeaderDiscipline.Sync = false;
                    drHeaderDiscipline.WebId = 0;
                    drHeaderDiscipline.Modified = DateTime.Now;
                    drHeaderDiscipline.Params = (chkFinal.Checked) ? "F" : string.Empty;
                    drHeaderDiscipline.StartTime = Convert.ToDateTime(dr["StartTime"]);
                    drHeaderDiscipline.SetWindNull();
                    drHeaderDiscipline.SetRealStartTimeNull();
                    drHeaderDiscipline.SetRealEndTimeNull();

                    drHeaderDiscipline["DisciplineCode"] = dr["DisciplineCode"];

                    // Update
                    dtDisciplineList.AddDisciplineListRow(drHeaderDiscipline);
                    taDisciplineList.Update(dtDisciplineList);
                }

                // Vytvori discipliny
                int autoOrder = DatabaseHelper.GetDisciplineListNewAutoOrder(Convert.ToInt32(drHeaderDiscipline["CompetitionId"]));
                for (int i = 1; i <= heatCount; i++)
                {
                    dtSplitHeader = dtDisciplineList.Copy();
                    
                    dtSplitHeader.Rows[0].SetAdded();
                    dtSplitHeader.Rows[0]["ParentId"] = this.drHeaderDiscipline["ID"];
                    dtSplitHeader.Rows[0]["WebId"] = 0;
                    dtSplitHeader.Rows[0]["Sync"] = false;
                    dtSplitHeader.Rows[0]["Status"] = 1;
                    dtSplitHeader.Rows[0]["AutoOrder"] = autoOrder + i - 1;

                    if (rbSeparated.Checked)
                    {
                        dtSplitHeader.Rows[0]["Name"] = header + " " + i.ToString();
                    }

                    if (rbTogether.Checked)
                    {
                        dtSplitHeader.Rows[0]["Name"] = header + " " + (char)(i + 64);
                    }

                    dtSplitHeader.Rows[0]["SecondaryOrder"] = i;

                    if (chkFinal.Checked)
                        dtSplitHeader.Rows[0]["Params"] = "F";
                    else
                        dtSplitHeader.Rows[0]["Params"] = string.Empty;

                    taDisciplineList.Update(dtSplitHeader.Rows[0]);
                }

            }
            catch (Exception ex)
            {
                ExceptionHelper.ShowErrorInfo(ex);
                return;
            }

            #endregion

            #region Presun pretekarov

            try
            {
                if (this.chkMovePerformances.Checked)
                {

                    this.dtDisciplineList = DatabaseHelper.GetDisciplineListByParentIdActive(Convert.ToInt32(this.drHeaderDiscipline["ID"]));
                    this.dtPerformances = DatabaseHelper.GetPerformancesByDisciplineListId(Convert.ToInt32(this.tnDiscipline.Name));

                    // Disciplíny sa zoradia podľa [SecondaryOrder], [Name]
                    DataRow[] aDisciplineList = dtDisciplineList.Select(null, "SecondaryOrder, Name");

                    #region Sorting
                    
                    DataRow[] aPerformances;
                    string sOrderBy;
                    switch (Convert.ToInt32(this.drHeaderDiscipline["DisciplineCode"]))
                    {
                        case Globals.SprintCode:
                        case Globals.LongRunCode:
                        case Globals.MarathonCode:
                            sOrderBy = "SB ASC, PB ASC, StartNumber DESC, Surname DESC, FirstName DESC";
                            foreach (DataRow dr in dtPerformances.Rows)
                            {
                                if (Convert.ToInt32(dr["SB"]) == 0)
                                    dr["SB"] = int.MaxValue;

                                if (Convert.ToInt32(dr["PB"]) == 0)
                                    dr["PB"] = int.MaxValue;
                            }
                            aPerformances = this.dtPerformances.Select(null, sOrderBy);
                            foreach (DataRow dr in aPerformances)
                            {
                                if (Convert.ToInt32(dr["SB"]) == int.MaxValue)
                                    dr["SB"] = 0;

                                if (Convert.ToInt32(dr["PB"]) == int.MaxValue)
                                    dr["PB"] = 0;
                            }
                            break;

                        case Globals.ThrowsCode:
                        case Globals.HorJumpCode:
                        case Globals.VerJumpCode:
                            sOrderBy = "SB DESC, PB DESC, StartNumber ASC, Surname ASC, FirstName ASC";
                            aPerformances = this.dtPerformances.Select(null, sOrderBy);
                            break;

                        default:
                            aPerformances = new DataRow[0];
                            break;
                    }

                    #endregion

                    /* NAJLEPŠÍ SPOLU 
                     * Zoradení pretekári sa priraďujú postupne do disciplín, dráhy sa priraďujú podľa výhodnosti.
                     * Najlepší pretekári do prvej disciplíny. */
                    if (rbTogether.Checked)
                    {
                        splitCount = 0;
                        foreach (DataRow drDiscList in aDisciplineList)
                        {
                            for (int i = 0; i < Globals.ActiveCompetition.LanesCount; i++)
                            {
                                if (splitCount + i >= aPerformances.Count())
                                    break;

                                aPerformances[splitCount + i]["DisciplineListId"] = drDiscList["ID"];
                                aPerformances[splitCount + i]["Lane"] = Globals.ActiveCompetition.LanesQuality[i];
                            }

                            splitCount += Globals.ActiveCompetition.LanesCount;
                        }

                        taPerformances.Update(aPerformances);
                    }

                    /* NAJLEPŠÍ ODDELENE
                     * Zoradeným pretekárom sa postupne priraďujú dráhy, najskôr najvýhodnejšia vo všetkých disciplínach.
                     * Najlepší pretekári do najvýhodnejšej dráhy. */
                    if (rbSeparated.Checked)
                    {
                        splitCount = 0;
                        for (int i = 0; i < Globals.ActiveCompetition.LanesCount; i++)
                        {
                            for (int j = 0; j < aDisciplineList.Count(); j++)
                            {
                                if (splitCount + j >= aPerformances.Count())
                                    break;

                                aPerformances[splitCount + j]["DisciplineListId"] = aDisciplineList[j]["ID"];
                                aPerformances[splitCount + j]["Lane"] = Globals.ActiveCompetition.LanesQuality[i];
                            }

                            splitCount += aDisciplineList.Count();
                        }

                        taPerformances.Update(aPerformances);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Pri presune pretekárov vznikla chyba!" + Environment.NewLine + ex.Message, "Rozdeliť disciplínu", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
                this.Close();
            }

            #endregion

        }
    
    
    
    }
}
